package notify

import (
	"context"
	Conf "cronjob_work/common/config"
	"cronjob_work/common/notify/wechart"
	"github.com/gogf/gf/v2/frame/g"
	"time"
)

type Wechat struct {
	Accounts map[string]string
	Content  string
}

var WechatChan chan *Wechat
var WechatKey string

func init() {
	ctx := context.Background()
	noticeConfig := Conf.Newconfig()
	WechatKey = noticeConfig.GetString(ctx, "wechat.key")
	poolSize := noticeConfig.GetInt(ctx, "wechat.pool")

	//创建通道
	WechatChan = make(chan *Wechat, poolSize)

	go func() {
		for {
			select {
			case m, ok := <-WechatChan:
				if !ok {
					return
				}
				if err := m.SendWechat(m.Content); err != nil {
					g.Log().Error(ctx, "SendWechat:", err.Error())
				}
			}
		}
	}()

}

func SendWechatToChan(accounts map[string]string, content string) bool {
	wechat := &Wechat{
		Accounts: accounts,
		Content:  content,
	}

	select {
	case WechatChan <- wechat:
		return true
	case <-time.After(time.Second * 10):
		return false
	}
}

func (s *Wechat) SendWechat(content string) error {
	send := wechart.NewSendMsg(WechatKey, true)
	send.Send("", content)
	time.Sleep(1 * time.Second)
	return nil
}
